package com.example.studentapp.diary;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.studentapp.MainActivity;
import com.example.studentapp.R;
import com.example.studentapp.db.SQLiteDB;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddDiaryActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView diary_add_returnIV,diary_upload1IV,diary_upload2IV,diary_upload3IV;
    TextView diary_add_saveTV;
    EditText diary_titleET,diary_contentET;
    Spinner diary_weaSP;
    String uploadPath1="";
    String uploadPath2="";
    String uploadPath3="";
    SQLiteDB sqLiteDB;
    SQLiteDatabase sqLiteDatabase;

    int flag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_diary);
        init();
    }

    private void init() {
        diary_add_returnIV=findViewById(R.id.diary_add_returnIV);
        diary_add_saveTV=findViewById(R.id.diary_add_saveTV);
        diary_upload1IV=findViewById(R.id.diary_upload1IV);
        diary_upload2IV=findViewById(R.id.diary_upload2IV);
        diary_upload3IV=findViewById(R.id.diary_upload3IV);
        diary_titleET=findViewById(R.id.diary_titleET);
        diary_weaSP=findViewById(R.id.diary_weaSP);
        diary_contentET=findViewById(R.id.diary_contentET);
        diary_add_returnIV.setOnClickListener(this);
        diary_add_saveTV.setOnClickListener(this);
        diary_upload1IV.setOnClickListener(this);
        diary_upload2IV.setOnClickListener(this);
        diary_upload3IV.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.diary_add_returnIV:
                finish();
                break;
            case R.id.diary_add_saveTV:
                // 添加日记
                String title = diary_titleET.getText().toString();
                String content = diary_contentET.getText().toString();
                String weather = (String) diary_weaSP.getSelectedItem();
                if(title.length() > 0 && content.length()>0&&weather.length()>0){
                    try{
                        sqLiteDB = new SQLiteDB(getApplicationContext());
                        sqLiteDatabase = sqLiteDB.getWritableDatabase();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String record_date = simpleDateFormat.format(new Date());
                        String insertSql="insert into diary(title,weather,content,upload_pic1,upload_pic2,upload_pic3,record_date)" +
                                " values('"+title+"','"+weather+"','"+content+"','"+uploadPath1+"','"+uploadPath2+"','"+uploadPath3+"','"+record_date+"')";
                        sqLiteDatabase.execSQL(insertSql);
                        // ？？
                        Intent intent = new Intent(AddDiaryActivity.this, MainActivity.class);
                        intent.putExtra("index",1);
                        startActivity(intent);
                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),
                                getString(R.string.diary_add_error),Toast.LENGTH_SHORT).show();

                    }
                }else{
                    Toast.makeText(getApplicationContext(),getString(R.string.diary_warn_null),Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.diary_upload1IV:
                // 从手机相册中获取图片
                flag = 1;
                callPics();
                break;
            case R.id.diary_upload2IV:
                //从手机相册中获取图片
                flag = 2;
                callPics();
                break;
            case R.id.diary_upload3IV:
                //从手机相册中获取图片
                flag = 3;
                callPics();
                break;
        }
    }
    // 这里 涉及到文件存储
    private void callPics() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,101);
    }

    // 打开手机相册后返回的请求

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == RESULT_CANCELED){
            Toast.makeText(getApplicationContext(),getString(R.string.diary_pic_no),Toast.LENGTH_SHORT).show();
            return;
        }
        if(requestCode==101){
            Uri uri = data.getData();
            ViewGroup.LayoutParams params = diary_upload1IV.getLayoutParams();
            params.width = 100;
            params.height =100;
            String savePic = Environment.getExternalStorageDirectory().getAbsolutePath()+"/StuAss";
            File file = new File(savePic);
            if(!file.exists()){
                file.mkdir();
            }
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String record_date=simpleDateFormat.format(new Date());
            savePic+="/"+record_date+flag+".png";
            OutputStream os = null;
            try{
                os = new FileOutputStream(new File(savePic));
                Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                bitmap.compress(Bitmap.CompressFormat.PNG,100,os);
                os.flush();
                os.close();
            }catch (Exception e){
                Toast.makeText(getApplicationContext(),getString(R.string.diary_pic_save_error),Toast.LENGTH_SHORT).show();

            }
            if(flag==1){
                uploadPath1=savePic;
                diary_upload1IV.setLayoutParams(params);
                diary_upload1IV.setImageURI(uri);
            } else if(flag==2){
                uploadPath2=savePic;
                diary_upload2IV.setLayoutParams(params);
                diary_upload2IV.setImageURI(uri);
            } else if(flag==3){
                uploadPath3=savePic;
                diary_upload3IV.setLayoutParams(params);
                diary_upload3IV.setImageURI(uri);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}